package com.qi.qipay.commons.utils;

import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class WebUtil {
    /**
     * 将request对象中的所有文件类型与字符串类型参数以key-value形式存储到map中返回
     *
     * @param request 传入的request对象
     * @return requestMap 将request对象打包好的map对象
     */
    public static Map<String, Object> getParamMap(MultipartHttpServletRequest request) {
        Enumeration<String> parameterNames = request.getParameterNames();
        Map<String, Object> requestMap=new HashMap<>();
        while (parameterNames.hasMoreElements()){
         String paramName=parameterNames.nextElement();
            if(request.getFile(paramName)==null){
                requestMap.put(paramName,request.getAttribute(paramName));
            }else {
                requestMap.put(paramName,request.getFile(paramName));
            }
        }
        return requestMap;
    }

    /**
     * 将request对象中的所有文件类型与字符串类型参数以key-value形式存储到map中返回
     *
     * @param request 传入的request对象
     * @return requestMap 将request对象打包好的map对象
     */
    public static Map<String, Object> getParamMap(HttpServletRequest request) {
        Enumeration<String> parameterNames = request.getParameterNames();
        Map<String, Object> requestMap = new HashMap<>();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            requestMap.put(parameterName, request.getParameter(parameterName));
        }
        // TODO 总感觉哪里有问题
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
            while (fileNames.hasNext()) {
                String fileName = fileNames.next();
                requestMap.put(fileName, multipartHttpServletRequest.getFile(fileName));
            }
        }
        return requestMap;
    }
}
